<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名"
          clearable
          size="small"
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择类型"
          clearable
          size="small"
          style="width: 200px"
        >
          <el-option label="收入" value="1" />
          <el-option label="支出" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="记录标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入记录标题"
          clearable
          size="small"
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <!-- 积分记录新增功能已隐藏 -->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['points:record:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['points:record:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['points:record:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="recordList"
      @selection-change="handleSelectionChange"
      border
      stripe
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="记录ID" align="center" prop="id" />
      <el-table-column label="用户名" align="center" prop="sysYouYouUser.userName" />
      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          <el-tag :type="scope.row.type === 1 ? 'success' : 'danger'">
            {{ scope.row.type === 1 ? "收入" : "支出" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="积分数" align="center" prop="amount" />
      <el-table-column label="记录标题" align="center" prop="title" />
      <el-table-column label="记录描述" align="center" prop="description" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['points:record:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['points:record:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改积分记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 隐藏ID字段，确保修改时能正确传递ID -->
        <el-form-item prop="id" hidden>
          <el-input v-model="form.id" />
        </el-form-item>
        <!-- 隐藏用户ID字段，确保记录归属正确 -->
        <el-form-item prop="userId" hidden>
          <el-input v-model="form.userId" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select
            v-model="form.type"
            placeholder="请选择类型"
            style="width: 100%"
            value-key="value"
          >
            <el-option label="收入" value="1" />
            <el-option label="支出" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="积分数" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入积分数" type="number" />
        </el-form-item>
        <el-form-item label="记录标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入记录标题" />
        </el-form-item>
        <el-form-item label="记录描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入记录描述" type="textarea" rows="3" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRecordWithUser,
  getRecord,
  delRecord,
  addRecord,
  updateRecord,
} from "@/api/points/record";
import { parseTime } from "@/utils/ruoyi";

export default {
  name: "Record",
  dicts: ["points_type", "sys_deleted_status"],

  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      recordList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        type: null,
        title: null, // 标题查询参数
      },
      form: {
        id: null,
        userId: null, // 用户ID，确保修改时传递
        type: null,
        amount: null,
        title: null,
        description: null,
      },
      rules: {
        type: [
          {
            required: true,
            message: "类型：收入/支出不能为空",
            trigger: "change",
          },
        ],
        amount: [{ required: true, message: "积分数不能为空", trigger: "blur" }],
        title: [
          { required: true, message: "记录标题不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    parseTime,
    /** 查询积分记录列表 */
    async getList() {
      this.loading = true;
      try {
        // 创建查询参数的副本，并确保type参数是数字类型
        const params = { ...this.queryParams };
        if (params.type !== null && params.type !== undefined && params.type !== '') {
          params.type = Number(params.type);
        }

        const response = await listRecordWithUser(params);
        this.recordList = response.rows || [];
        this.total = response.total || 0;
      } catch (error) {
        console.error("查询接口调用失败:", error);
        this.recordList = [];
        this.total = 0;
        this.$message.error("查询接口异常，请重试");
      } finally {
        this.loading = false;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        userId: null,
        type: "1", // 默认设置为增加
        amount: null,
        title: null,
        description: null,
      };
      this.$refs.form && this.$refs.form.resetFields();
    },
    handleQuery() {
      this.queryParams.pageNum = 1; // 重置页码为第一页
      this.getList();
    },
    resetQuery() {
      // 清空查询表单
      this.$refs.queryForm.resetFields();
      // 重置页码
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleUpdate(row) {
      this.reset();
      // 从行数据中获取完整信息（包括ID和用户ID）
      getRecord(row.id).then((response) => {
        if (response.code === 200 && response.data) {
          this.form = {
            ...response.data,
            userId: response.data.userId || row.userId, // 确保用户ID被正确赋值
          };
          this.open = true;
          this.title = "修改积分记录";
        } else {
          this.$message.error("获取记录详情失败：" + (response?.msg || "数据异常"));
        }
      }).catch(error => {
        console.error("获取修改数据失败:", error);
        this.$message.error("获取数据异常，请重试");
      });
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 确保ID存在（必填）
          if (!this.form.id) {
            this.$message.error("记录ID不存在，无法修改");
            return;
          }
          updateRecord(this.form).then((response) => {
            if (response.code === 200) {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList(); // 重新加载列表
            } else {
              this.$message.error("修改失败：" + (response.msg || "操作异常"));
            }
          }).catch(error => {
            console.error("修改接口调用失败:", error);
            this.$message.error("修改接口异常，请重试");
          });
        }
      });
    },
    handleDelete(row) {
      const ids = row ? [row.id] : this.ids; // 处理单行删除和批量删除
      if (!ids || ids.length === 0) {
        this.$message.warning("请选择要删除的记录");
        return;
      }
      this.$modal
        .confirm(`是否确认删除选中的${ids.length}条积分记录？`)
        .then(() => {
          delRecord(ids).then((response) => {
            if (response.code === 200) {
              this.$modal.msgSuccess("删除成功");
              this.getList(); // 重新加载列表
            } else {
              this.$message.error("删除失败：" + (response.msg || "操作异常"));
            }
          }).catch(error => {
            console.error("删除接口调用失败:", error);
            this.$message.error("删除接口异常，请重试");
          });
        })
        .catch(() => {});
    },
    handleExport() {
      this.download(
        "points/record/export",
        { ...this.queryParams },
        `record_${Date.now()}.xlsx`
      );
    },
  },
};
</script>
